package com.homework.servlet.client;

import com.google.gson.Gson;
import com.homework.entity.User;
import com.homework.factory.ServiceFactory;
import com.homework.service.UserService;
import com.homework.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/client/login.do")
public class LoginServlet extends BaseServlet {
    UserService userService= ServiceFactory.getUserService();

    public void login(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        User user = userService.LoginUser(username, password);
        if (user==null){
            writer.write(new Gson().toJson("0"));
            //用户名或密码不能为空
            return;
        }
        req.getSession().setAttribute("user",user);
        Integer count = (Integer)req.getServletContext().getAttribute("count");
        if (count==null){
            count=1;
        }else {
            count++;
        }
        req.getServletContext().setAttribute("count",count);
        writer.write(new Gson().toJson(count+""));
    }

    public void keeplogin(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        User user = (User)req.getSession().getAttribute("user");
        String username = user.getUsername();
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(new Gson().toJson(username));
    }

}
